import {useState,useEffect} from "react"

const useKeyPress=(targetKeyCode)=>{
    const [ keyCode,setKeyCode ] = useState(false)
    useEffect(()=>{
        const handleKeyDown= ({keyCode})=>{
            if(keyCode === targetKeyCode){
              setKeyCode(true)
            }
        }
        const handleKeyUp = ({keyCode})=>{
            if(keyCode === targetKeyCode){
              setKeyCode(false)
            }
        }

        document.addEventListener('keyup',handleKeyUp);
        document.addEventListener('keydown',handleKeyDown);

        return ()=>{
          document.removeEventListener('keyup',handleKeyUp)
          document.removeEventListener('keydown',handleKeyDown)
        }
    },[])
    return keyCode
}

export default useKeyPress
